#include "Image.h"
#include "Color.h"
#include <exception>

using namespace SolidityEngine;



Image::Image(int width, int height, const Color32& color):
    _rendersurface(NULL)
{
    Uint32 rmask, gmask, bmask, amask;
    #if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x000000ff;
    #else
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0xff000000;
    #endif
    _rendersurface=SDL_CreateRGBSurface(SDL_HWSURFACE|SDL_SRCALPHA,width,height,32,rmask,gmask,bmask,amask);
    if(_rendersurface) SDL_FillRect(_rendersurface,&(_rendersurface->clip_rect),color.GetPixelValue(_rendersurface));
}

Image::~Image(){
    SDL_FreeSurface(_rendersurface);
}

SDL_Surface* Image::GetSurface(){
    return _rendersurface;
}

const SDL_Surface* Image::GetSurface() const{
    return _rendersurface;
}

int Image::Width() const{
    if(_rendersurface) return _rendersurface->w;
    return 0;
}
int Image::Height() const{
    if(_rendersurface) return _rendersurface->h;
    return 0;
}

///Use with EXTREME caution!!
void* Image::Pixels(){
    if(_rendersurface) return _rendersurface->pixels;
    return NULL;
}

Rect Image::GetClipRect() const{
    if(_rendersurface){
        return Rect(_rendersurface->clip_rect.x,_rendersurface->clip_rect.y,_rendersurface->clip_rect.w,_rendersurface->clip_rect.h);
    }
    return Rect(0,0,0,0);
}

void Image::SetClipRect(const Rect& rect){
    SDL_Rect srect;
    srect.x=rect.X();
    srect.y=rect.Y();
    srect.w=rect.Width();
    srect.h=rect.Height();
    SDL_SetClipRect(_rendersurface,&srect);
}
